package com.kob.botrunningsystem.service.impl.utils;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BotPool extends Thread {  // 生产者消费者模型
    private final static ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();  // 条件变量，好像和唤醒线程有关？
    private final Queue<Bot> bots = new LinkedList<Bot>();  // 这个队列不是线程安全的，我们需要自己将其管理成线程安全的

    public void addBot(Integer userID, String botCode, String input) {
        lock.lock();
        try {
            bots.add(new Bot(userID, botCode, input));
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    private void consume(Bot bot) {
        Consumer consumer = new Consumer();
        consumer.startTimeout(2000, bot);
    }

    @Override
    public void run() {
        while (true) {
            lock.lock(); // 防止读写冲突
            if (bots.isEmpty()) {
                try {
                    condition.await();  // bots为空，阻塞住当前线程,里面默认包含锁释放操作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            } else {
                Bot bot = bots.remove();  // 去除并且删除队头
                lock.unlock();

                consume(bot); // 比较耗时，可能需要几秒钟
            }
        }
    }
}
